<template>
  <div class="contioner" v-loading="pageData.loadingUp">
    <a-tabs :lazy-load="true" justify @change="tabChange" :default-active-key="pageData.active">
      <a-tab-pane key="1" title="固定资产调拨">
        <pageTabelLayout>
          <template #pageHeader>
            <div class="my-tool-bar" style="margin-bottom: 5px">
              <a-space>
                <el-button type="primary" :icon="Search" @click="getList">查询</el-button>
                <el-button type="success" :icon="CirclePlus" @click="newData('新增')"
                  >新增</el-button
                >
                <el-button :icon="EditPen" @click="audit">审核</el-button>
                <el-button plain @click="TurnDown">驳回</el-button>
                <el-button plain :icon="Delete" @click="deleteData">删除</el-button>
              </a-space>
            </div>
          </template>
          <!-- <div style="background-color: #f0f2f5; height: 10px"></div> -->
          <template #pageTabel>
            <encapsulation-agrid
              ref="refgridOption"
              :configaggrid="configaggrid"
            ></encapsulation-agrid>
          </template>
        </pageTabelLayout>
      </a-tab-pane>
      <a-tab-pane key="2" title="固定资产调拨已审核">
        <pageTabelLayout>
          <template #pageHeader>
            <div class="search-form isheader" v-show="pageData.headerShow">
              <a-form size="small" :model="query" layout="inline">
                <CorporateSectorCascader
                  :style="{ width: '200px' }"
                  :configCascader="configCascader"
                  @changeCascader="changeCascader"
                />
                <a-form-item label="调拨人">
                  <a-input
                    allow-clear
                    :style="{ width: '180px' }"
                    class="bacClass"
                    v-model="pageData.needPerson"
                  />
                </a-form-item>
                <a-form-item label="调拨单号">
                  <a-input
                    allow-clear
                    :style="{ width: '180px' }"
                    class="bacClass"
                    v-model="pageData.needCode"
                  />
                </a-form-item>
                <a-form-item label="审核状态">
                  <a-select
                    allow-clear
                    :style="{ width: '180px' }"
                    class="bacClass"
                    v-model="pageData.auditState"
                  >
                    <a-option value="1">审核通过</a-option>
                    <a-option value="2">驳回</a-option>
                  </a-select>
                </a-form-item>
              </a-form>
            </div>
            <div class="my-divisders">
              <a-divider orientation="center">
                <icon-double-up
                  v-if="pageData.headerShow"
                  @click="pageData.headerShow = false"
                  :strokeWidth="2"
                  :size="18"
                />
                <icon-double-down
                  v-else
                  @click="pageData.headerShow = true"
                  :strokeWidth="2"
                  :size="18"
                />
              </a-divider>
            </div>
            <div class="my-tool-bar">
              <a-space>
                <el-button type="primary" :icon="Search" @click="getList">查询</el-button>
              </a-space>
            </div>
          </template>
          <!-- <div style="background-color: #f0f2f5; height: 10px"></div> -->
          <template #pageTabel>
            <encapsulation-agrid
              ref="refgridOption1"
              :configaggrid="configaggrid1"
            ></encapsulation-agrid>
          </template>
        </pageTabelLayout>
      </a-tab-pane>
    </a-tabs>

    <a-drawer
      cancel-text="关闭"
      ok-text="保存"
      popup-container=".arco-tabs-content"
      height="91vh"
      placement="bottom"
      :visible="pageData.showAdd"
      unmountOnClose
      @cancel="pageData.showAdd = false"
      @ok="save"
      :mask-closable="false"
    >
      <template #title> {{ pageData.type }}</template>
      <el-form ref="ruleFormRef" :model="query" label-width="88px" class="demo-query" status-icon>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="调拨单号" prop="shiftCode">
              <el-input v-model="query.shiftCode" style="width: 200px" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6" style="display: flex">
            <!-- <el-form-item label="调出公司" prop="shiftCompanyName">
              <el-input v-model="query.shiftCompanyName" style="width: 200px" disabled />
            </el-form-item> -->
            <CorporateSectorCascader
              ref="cascaderRef3"
              :configCascader="configCascader3"
              @changeCascader="changeCascader3"
            />
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="调出部门" prop="departmentName">
              <el-input v-model="query.departmentName" style="width: 200px" disabled />
            </el-form-item>
          </el-col> -->
          <el-col :span="6">
            <el-form-item
              label="调拨时间"
              prop="shiftTime"
              :rules="[{ required: true, message: '调拨时间必选' }]"
            >
              <el-date-picker
                type="date"
                placeholder="选择调拨时间"
                v-model="query.shiftTime"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 200px"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <CorporateSectorCascader
              ref="cascaderRef1"
              :configCascader="configCascader1"
              @changeCascader="changeCascader1"
            />
          </el-col> -->
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6" style="display: flex">
            <CorporateSectorCascader
              ref="cascaderRef2"
              :configCascader="configCascader2"
              @changeCascader="changeCascader2"
            />
          </el-col>
          <el-col :span="6">
            <el-form-item label="调拨人" prop="shiftPerson">
              <el-input v-model="query.shiftPerson" style="width: 200px" disabled />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="借用仓库" prop="warehouseId">
              <el-select  v-model="query.warehouseId"  style="width: 200px" :disabled="( query.inCompanyID == query.shiftCompanyID) || !query.inCompanyID" >
                <el-option v-for="item in warehouseNameList" :key="item.id" :label="item.warehouseName" :value="item.id"  />
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="6">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="query.remark" style="width: 200px" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item
              label="机台名称"
              prop="mechanicalCode"
              :rules="[{ required: true, message: '机台名称必选' }]"
            >
              <el-select-v2
                v-model="query.mechanicalCode"
                :options="repairmanList"
                placeholder="选择机台名称"
                filterable
                :loading="pageData.loadingUp"
                clearable
                @change="selectV2"
                size="default"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="机台区域"
              prop="district"
              :rules="[{ required: true, message: '机台区域必选' }]"
            >
              <el-input v-model="query.district" style="width: 200px" disabled />
            </el-form-item>
          </el-col> -->
        </el-row>
        <!-- <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item
              label="机台编号"
              prop="mechanicalCode"
              :rules="[{ required: true, message: '机台编号必选' }]"
            >
              <el-input v-model="query.mechanicalCode" style="width: 200px" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="入厂时间"
              prop="joinFactoryTime"
              :rules="[{ required: true, message: '入厂时间必选' }]"
            >
              <el-input v-model="query.joinFactoryTime" style="width: 200px" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="折旧时长"
              prop="scrapTime"
              :rules="[{ required: true, message: '折旧时长必选' }]"
            >
              <el-input v-model="query.scrapTime" style="width: 200px" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="已折旧时间"
              prop="deprecitionTime"
              label-width="95px"
              :rules="[{ required: true, message: '已折旧时间必选' }]"
            >
              <el-input v-model="query.deprecitionTime" style="width: 190px" disabled />
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row :gutter="24">
          <!-- <el-col :span="6">
            <el-form-item
              label="转移后差异分摊"
              prop="shiftShare"
              label-width="125px"
              :rules="[{ required: true, message: '转移后差异分摊必选' }]"
            >
              <el-input v-model="query.shiftShare" style="width: 165px" disabled />
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <div class="hengxian"></div>
      <el-button style="margin-left: 15px" :icon="CirclePlus" @click="addWorkbench" type="success"
        >选取固定资产</el-button
      >
      <el-button style="margin-left: 30px" :icon="Delete" @click="deleteWorkbench" type="warning"
        >删除</el-button
      >
      <div :style="{ height: '78%', padding: '10px' }" style="background: #fff">
        <encapsulation-agrid
          ref="refgridOption2"
          :configaggrid="configaggrid2"
        ></encapsulation-agrid>
      </div>
    </a-drawer>
    <a-drawer
      cancel-text="关闭"
      ok-text="保存"
      popup-container=".arco-tabs-content"
      height="91vh"
      placement="bottom"
      :visible="pageData.workbenchShowAdd"
      unmountOnClose
      @cancel="stockKeeping1"
      @ok="stockKeeping"
      :mask-closable="false"
      style="z-index: 999"
    >
      <template #title> 选取固定资产 </template>
      <div style="width: 100%; height: 90%">
        <el-form :model="query" label-width="100px" class="demo-query" status-icon size="default">
          <el-row :gutter="0">
            <el-col :span="4">
              <el-form-item label="物料名称" prop="mechanicalName">
                <!-- <el-select-v2
                  v-model="query1.mechanicalName"
                  :options="MaterialNameList"
                  placeholder="选择物料名称"
                  filterable
                  :loading="pageData.loadingUp"
                  clearable
                  size="default"
                /> -->
                <el-input v-model="query1.materialName" placeholder="输入物料名称" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="物料编号" prop="materialCode">
                <!-- <el-select-v2
                  v-model="query1.materialCode"
                  :options="MaterialNumberList"
                  placeholder="选择物料编号"
                  filterable
                  :loading="pageData.loadingUp"
                  clearable
                  size="default"
                /> -->
                <el-input v-model="query1.materialCode" placeholder="输入物料编号" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="固定资产编号">
                <el-input v-model="query1.numberId" placeholder="输入固定资产编号" />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="4">
              <el-form-item label="物料编号" prop="materialCode">
                <el-select-v2
                  v-model="query1.materialCode"
                  :options="MaterialNumberList"
                  placeholder="选择物料编号"
                  filterable
                  :loading="pageData.loadingUp"
                  clearable
                  size="default"
                />
              </el-form-item>
            </el-col> -->
            <el-col :span="4">
              <!-- <CorporateSectorCascader ref="cascaderRef4" :configCascader="configCascader4"
                @changeCascader="changeCascader4" /> -->
              <a-form-item label-col-flex="70px" label="部门" class="ml-3">
                <a-cascader
                  v-model="query1.outDepartmentId"
                  :options="pageData.bmList"
                  allow-clear
                  ref="casOb1"
                  popup-container="html"
                />
              </a-form-item>
            </el-col>
            <el-col :span="4">
              <el-button
                style="margin-left: 20px"
                type="primary"
                :icon="Search"
                @click="workbenchGetList"
                >查询</el-button
              >
            </el-col>
          </el-row>
        </el-form>
        <encapsulation-agrid
          ref="refgridOption3"
          :configaggrid="configaggrid3"
          @SelectionChanged="selectionChange"
        ></encapsulation-agrid>
      </div>
    </a-drawer>
    <el-dialog
      align-center
      style="width: 1200px; height: 450px"
      v-model="pageData.dialogFormVules"
      v-loading="loadingElplus"
    >
      <!-- <div style="width: 100%; height: 450px"> -->
      <AgGridVuesCopys
        :rowHeight="33"
        :headerHeight="33"
        :suppressCopyRowsToClipboard="true"
        rowSelection="multiple"
        @grid-ready="gridReady"
        style="height: 37vh"
        :defaultColDef="defaultColDef"
        class="ag-theme-alpine"
        :rowData="pageData.dataListOP"
        :columnDefs="tableColumns4"
        :localeText="localeText1"
      >
      </AgGridVuesCopys>
      <!-- </div> -->
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
  // 引入element提示
  import { ElMessage, ElMessageBox } from 'element-plus'
  //引入封装post
  
  import { localeText } from '@/api/aggridZw'
  import { post } from '@/api/http'
  import {
    tableColumns,
    tableColumns1,
    tableColumns2,
    tableColumns3,
    tableColumns4,
  } from './TransferOfFixedAssets'
  import buttionRender from '@/components/aggridCellRenDerer/buttionRender.vue'
  import { Search, Delete, CirclePlus, EditPen } from '@element-plus/icons-vue'
  import CorporateSectorCascader from '@/components/corporateSectorCascader1/index.vue'
  import emitter from '@/hooks/useEventBus'
  import { slicing } from '@/utils/caseFrimAndSecRig'
  import dayjs from 'dayjs'
  const loadingElplus = ref(false)
  let pageData = reactive<any>({
    showAdd: false,
    workbenchShowAdd: false,
    type: '',
    loadingUp: false,
    active: '1',
    headerShow: true,
    id: '',
    companyID: '',
    companyName: '',
    mechanicalCode: '',
    mechanicalName: '',
    needCode: '',
    needPerson: '',
    departmentName: '',
    departmentID: '',
    dialogFormVules: false,
    dataListOP: [],
    bmList: [],
    auditState: '',
  })

  let query = reactive<any>({
    mechanicalCode: '',
    shiftCompanyName: '',
    departmentName: '',
    departmentID: '',
    shiftCode: '',
    district: '',
    companyID: '',
    joinFactoryTime: '',
    deprecitionTime: '',
    upDeprecitionTime: '',
    shiftShare: '',
    shiftTime: dayjs(new Date()).format('YYYY-MM-DD'),
    shiftPerson: '',
    warehouseId: '',
    warehouseName: '',
    warehouseTypeName: '',
  })
  let query1 = reactive<any>({
    deleteState: 0,
    mechanicalName: '',
    materialCode: '',
    companyId: query.shiftCompanyID,
    outDepartmentId: '',
    numberId: '',
  })
  tableColumns.push({
    headerName: '操作',
    field: 'ouihadpc',
    resizable: 'false',
    sortable: 'false',
    width: 120,
    filter: false,
    // lockPosition: 'right',
    pinned: 'right',
    cellRenderer: buttionRender,
    cellRendererParams: {
      buttonList: [
        {
          type: 'success',
          text: '修改',
          typeName: 'el-button',
          Callback: (data: any) => {
            console.log(data)
            for (let key in data) {
              query[key] = data[key]
            }
            newData('修改', data)
          },
        },
        {
          type: 'success',
          text: '详情',
          typeName: 'el-button',
          Callback: (data: any) => {
            for (let key in data) {
              query[key] = data[key]
            }
            newData('详情', data)
          },
        },
      ],
      eltagSize: 0,
    },
  })
  tableColumns1.push({
    headerName: '操作',
    field: 'ouihadpc',
    resizable: 'false',
    filter: false,
    sortable: 'false',
    width: 120,
    // lockPosition: 'right',
    pinned: 'right',
    cellRenderer: buttionRender,
    cellRendererParams: {
      buttonList: [
        {
          type: 'success',
          text: '详情',
          typeName: 'el-button',
          Callback: (data: any) => {
            for (let key in data) {
              query[key] = data[key]
            }
            newData('详情', data)
          },
        },
      ],
      eltagSize: 0,
    },
  })
  let form = reactive<any>({
    deleteState: 0,
    auditState: 0,
  })
  let cascaderRef = ref('')
  let configCascader = ref<{}>({
    corporateWidth: '180px', //公司宽度
    sectorWidth: '180px', //部门宽度
    corporateRquired: false, //公司是否必填
    sectorRquired: false, //部门是否必填
    size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
    corporateName: '调入公司', //公司label
    sectorName: '调入部门', //部门label
    cascaderShow: false, //配置部门不显示
  })
  const changeCascader = (data: any) => {
    console.log(data)
    const { corporateId, corporateLabel, sectorLabel, sectorId } = data
    pageData.companyName = corporateLabel
    pageData.companyID = corporateId
    pageData.departmentName = sectorLabel
    pageData.departmentID = sectorId
  }
  let cascaderRef1 = ref()
  // let configCascader1 = ref<{}>({
  //   corporateWidth: '65%', //公司宽度
  //   sectorWidth: '65%', //部门宽度
  //   corporateRquired: true, //公司是否必填
  //   sectorRquired: true, //部门是否必填
  //   size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
  //   corporateName: '借用公司', //公司label
  //   sectorName: '借用部门', //部门label
  //   cascaderShow: '', //配置部门不显示
  //   sectorNameLabelWidth: '78px',
  //   corporateNameLabelWidth: '78px',
  // })
  const configCascader1 = ref<{}>({
    corporateWidth: '65%', //公司宽度
    size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
    corporateName: '公司', //公司label
    cascaderShow: 'sector', //配置部门不显示
    corporateRquired: false,
    corporateNameLabelWidth: '78px',
  })
  const changeCascader1 = (data: any) => {
    const { corporateId, corporateLabel, sectorLabel, sectorId } = data
    query.companyName = corporateLabel
    query.companyID = corporateId
    // query.needDepartmentName = sectorLabel
    // query.needDepartmentID = sectorId
  }
  let cascaderRef2 = ref()
  let configCascader2 = ref<{}>({
    corporateWidth: '190px', //公司宽度
    sectorWidth: '190px', //部门宽度
    corporateRquired: true, //公司是否必填
    sectorRquired: true, //部门是否必填
    size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
    corporateName: '调入公司', //公司label
    sectorName: '调入部门', //部门label
    cascaderShow: 'sector', //配置部门不显示
    sectorNameLabelWidth: '78px',
    corporateNameLabelWidth: '78px',
  })
  const warehouseNameList = ref<any>([])
  const changeCascader2 = async (data: any) => {
    console.log(data)

    const { corporateId, corporateLabel, sectorLabel, sectorId } = data
    query.inCompanyName = corporateLabel
    query.inCompanyID = corporateId
    query.shiftDepartmentName = sectorLabel
    query.shiftDepartmentID = sectorId
    emitter.emit('inCompanyName', query.inCompanyID)
    //如果是借用仓库禁用 则不用发请求获取数据
    resSert()
    if (query.inCompanyID == query.shiftCompanyID || !query.inCompanyID) {
      //先重置借用仓库的值
      query.warehouseName = ''
      return
    }
    const res = await post({
      url: 'wms/warehouse/getFieldValue2',
      data: {
        firmId: query.inCompanyID,
        warehouseName: '',
        warehouseTypeName: '五金仓',
      },
    })
    query.warehouseName = res.data[0].warehouseName
    query.warehouseId = res.data[0].id
    warehouseNameList.value = res.data
    console.log(query.warehouseName, res.data)
  }
  const resSert = () => {
    post({
      url: 'wms/warehouse/getFieldValue2',
      data: {
        firmId: query.inCompanyID,
        warehouseName: '',
        warehouseTypeName: '五金仓',
      },
    }).then((res: any) => {
      if (res.code === 200) {
        query.warehouseName = res.data[0].warehouseName
        query.warehouseTypeName = res.data[0].warehouseTypeName
        query.warehouseId = res.data[0].id
      }
    })
  }
  watch(
    () => query.warehouseId,
    (val) => {
      warehouseNameList.value.forEach((item: any) => {
        if (item.id == val) {
          query.warehouseName = item.warehouseName
          query.warehouseTypeName = item.warehouseTypeName
        }
      })
    }
  )
  let refgridOption = ref<any>()
  let refgridOption1 = ref<any>()
  let refgridOption2 = ref<any>()
  let refgridOption3 = ref<any>()
  const gridOption = ref()
  const gridReady = (params: any) => {
    gridOption.value = params.api
  }
  const defaultColDef = {
    sortable: true,
    resizable: true,
    filter: true,
  }
  const localeText1: any = ref(localeText)
  let configaggrid = ref({
    url: 'purchase/FixedShift/getPage', //接口路径
    queryData: {
      deleteState: 0,
      auditState: 0,
    },
    paginationShow: true, //分页是否显示
    invokeiIterface: true, //是否调用接口
    rowMultiSelectWithClick: true, //点击行是否多选
    column: tableColumns,
    fileName: 'TransferOfFixedAssets-1',
  })
  let configaggrid1 = ref({
    url: 'purchase/FixedShift/getPage', //接口路径
    queryData: {
      deleteState: 0,
      auditState: '12',
    },
    paginationShow: true, //分页是否显示
    invokeiIterface: true, //是否调用接口
    rowMultiSelectWithClick: true, //点击行是否多选
    column: tableColumns1,
    fileName: 'TransferOfFixedAssets-2',
  })
  let configaggrid2 = ref({
    url: '', //接口路径
    queryData: {
      deleteState: 0,
      auditState: 1,
    },
    paginationShow: false, //分页是否显示
    invokeiIterface: false, //是否调用接口
    rowMultiSelectWithClick: true, //点击行是否多选
    column: tableColumns3,
  })
  const isRowSelectable = (rowNode: any) => {
    console.log(rowNode.data.machineState, rowNode.data.subCategory)

    if (
      rowNode.data.machineState != 0 &&
      (rowNode.data.subCategory === '单面机' ||
        rowNode.data.subCategory === '双面机' ||
        rowNode.data.subCategory === '罗纹机')
    ) {
      return false
    }
    return true
  }

  let configaggrid3 = ref({
    url: 'wms/ironwareStockInfo/getList', //接口路径
    queryData: {
      mechanicalName: '',
      mechanicalCode: '',
      companyId: query.companyID,
      outDepartmentId: query.departmentID,
    },
    paginationShow: true, //分页是否显示
    invokeiIterface: false, //是否调用接口
    rowMultiSelectWithClick: true, //点击行是否多选
    column: tableColumns2,
    selectable: isRowSelectable,
    rowStyle: (rowNode: any) => {
      if (
        rowNode.data.machineState != 0 &&
        (rowNode.data.subCategory === '单面机' ||
          rowNode.data.subCategory === '双面机' ||
          rowNode.data.subCategory === '罗纹机')
      ) {
        return { background: 'lightgrey' }
      }
      return null
    },
  })
  let configaggrid4: any = ref({
    url: '', //接口路径
    queryData: {
      mechanicalName: '',
      mechanicalCode: '',
    },
    paginationShow: false, //分页是否显示
    invokeiIterface: false, //是否调用接口
    rowMultiSelectWithClick: true, //点击行是否多选
    column: tableColumns2,
    defaultData: [],
  })
  const workbenchGetList = () => {
    query1.outFirmId = query.shiftCompanyID
    // query1.outDepartmentId = query.departmentID
    refgridOption3.value.setQuery({ ...query1, stockState: 1 })
  }
  // //物料名称
  let MaterialNameList = ref<any>([])
  // //物料编号
  let MaterialNumberList = ref<any>([])
  //查询物料名称接口
  const MaterialNameFocus = async () => {
    try {
      pageData.loadingUp2 = true
      let res: any = await post({
        url: 'wms/ironwareStockInfo/getFieldValueTwo',
        data: {
          materialCode: '',
          filterMap: {
            outFirmId: query.companyID,
            outDepartmentId: query.departmentID,
            stockState: 1,
          },
        },
      })
      if (res.code == 200) {
        MaterialNumberList = res.data.map((item: any) => {
          return {
            value: item.materialCode,
            label: item.materialCode,
          }
        })
        pageData.loadingUp2 = false
        return
      }
      ElMessage.error(res.message)
    } finally {
      pageData.loadingUp2 = false
    }
  }
  //查询物料名称接口
  const MaterialNameFocus1 = async () => {
    try {
      pageData.loadingUp2 = true
      let res: any = await post({
        url: 'wms/ironwareStockInfo/getFieldValueTwo',
        data: {
          materialName: '',
          filterMap: {
            outFirmId: query.companyID,
            outDepartmentId: query.departmentID,
            stockState: 1,
          },
        },
      })
      if (res.code == 200) {
        MaterialNameList.value = res.data.map((item: any) => {
          return {
            value: item.materialName,
            label: item.materialName,
          }
        })
        pageData.loadingUp2 = false
        return
      }
      ElMessage.error(res.message)
    } finally {
      pageData.loadingUp2 = false
    }
  }
  //机台保存
  const stockKeeping = () => {
    let arr3 = refgridOption3.value.getSelectedRows()
    if (arr3.length == 0) {
      ElMessage.warning('请勾选您要选择的机台')
      return
    }
    let arr = refgridOption2.value.getListData()
    for (const item of arr) {
      const found = arr3.find((elem: any) => elem.numberId === item.numberId)
      if (!found) {
        arr3.push(item)
      }
    }
    const newArr = arr3.map((item: any) => {
      if (item.hasOwnProperty('fixedShiftState')) {
        return {
          ...item,
          fixedShiftState: 1,
        }
      }
      return item
    })
    console.log(newArr)
    refgridOption2.value?.setdataListIterface([...newArr])
    pageData.workbenchShowAdd = false
    query1.materialCode = ''
    query1.mechanicalName = ''
    query1.outDepartmentId = ''
  }
  const stockKeeping1 = () => {
    pageData.workbenchShowAdd = false
    query1.materialCode = ''
    query1.mechanicalName = ''
    query1.outDepartmentId = ''
  }
  //删除机台
  const deleteWorkbench = () => {
    const selectedData = refgridOption2.value.getSelectedRows()
    if (selectedData.length == 0) {
      ElMessage.warning('请勾选您要删除的单据')
      return
    }
    ElMessageBox.confirm('确认删除选中单据?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        refgridOption2.value.applyTransaction({ remove: refgridOption2.value.getSelectedRows() })
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      })
      .catch(() => {})
  }
  let lastSelectionList: any = []
  const selectionChange = (params: any) => {
    let SelectionList = refgridOption3.value.getSelectedRows()
    let checkRes = SelectionList.filter(
      (item: any) =>
        item.machineState != 0 &&
        (item.subCategory === '单面机' ||
          item.subCategory === '双面机' ||
          item.subCategory === '罗纹机')
    )
    if (checkRes.length > 0) {
      let str = checkRes.map((item: any) => item.numberId).join(',')
      ElMessage.error(`不允许勾选，固定资产编号${str}在机台设备维护内机台状态不是未启动`)
      params.api.forEachNode((node: any) => {
        const numberIdList = lastSelectionList.map((item: any) => item.numberId)
        if (numberIdList.includes(node.data.numberId)) {
          node.setSelected(true)
        } else {
          node.setSelected(false)
        }
      })
    }
    lastSelectionList = SelectionList
  }

  const addWorkbench = () => {
    pageData.workbenchShowAdd = true
    lastSelectionList = []
    nextTick(() => {
      workbenchGetList()
      MaterialNameFocus()
      MaterialNameFocus1()
      getBmGroup(query.shiftCompanyID)
    })
  }
  const newData = async (type: string, data?: any) => {
    pageData.type = type
    repairmanFocus()
    if (type == '新增') {
      for (let key in query) {
        if (key !== 'shiftTime') {
          query[key] = ''
        }
      }
      pageData.id = ''
      try {
        pageData.loadingUp = true
        let { code, message, data } = await post({
          url: 'purchase/FixedShift/getNeedCode',
        })
        if (code == 200) {
          pageData.loadingUp = false
          query.shiftCode = data
          acquisitionCompany()
          return
        }
        ElMessage.error(message)
      } finally {
        pageData.loadingUp = false
      }
    }
    if (type == '修改') {
      pageData.showAdd = true
      nextTick(() => {
        const {
          id,
          inCompanyName,
          inCompanyID,
          shiftDepartmentID,
          shiftDepartmentName,
          list,
          shiftCompanyName,
          shiftCompanyID,
          departmentName,
          departmentID,
        } = data
        let pam1 = {
          sectorId: departmentID,
          sectorLabel: departmentName,
          corporateId: shiftCompanyID,
          corporateLabel: shiftCompanyName,
        }
        let pam2 = {
          sectorId: shiftDepartmentID,
          sectorLabel: shiftDepartmentName,
          corporateId: inCompanyID,
          corporateLabel: inCompanyName,
        }
        console.log(list)
        cascaderRef3.value?.parentComponent(pam1)
        cascaderRef2.value?.parentComponent(pam2)
        post({
          url: 'purchase/FixedShiftDetail/getList',
          data: {
            fixedShiftID: id,
          },
        }).then(({ code, data }) => {
          if (code == 200) {
            refgridOption2.value.setdataListIterface([...data])
          }
        })
        pageData.id = id
      })
    }
    if (type == '详情') {
      post({
        url: 'purchase/FixedShiftDetail/getList',
        data: {
          fixedShiftID: data.id,
        },
      }).then(({ code, data }) => {
        if (code == 200) {
          pageData.dataListOP = data
        }
      })
      pageData.dialogFormVules = true
    }
  }

  let cascaderRef3: any = ref()
  let configCascader3 = ref<{}>({
    corporateWidth: '190px', //公司宽度
    sectorWidth: '190px', //部门宽度
    corporateRquired: true, //公司是否必填
    sectorRquired: true, //部门是否必填
    size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
    corporateName: '调出公司', //公司label
    sectorName: '调出部门', //部门label
    cascaderShow: 'sector', //配置部门不显示
    sectorNameLabelWidth: '78px',
    corporateNameLabelWidth: '78px',
  })
  const changeCascader3 = async (data: any) => {
    console.log(data)
    const { corporateId, corporateLabel, sectorLabel, sectorId } = data
    query.shiftCompanyName = corporateLabel
    query.shiftCompanyID = corporateId
    query.departmentName = sectorLabel
    query.departmentID = sectorId
  }

  // let cascaderRef4: any = ref()
  // let configCascader4 = ref<{}>({
  //   corporateWidth: '190px', //公司宽度
  //   sectorWidth: '190px', //部门宽度
  //   corporateRquired: false, //公司是否必填
  //   sectorRquired: false, //部门是否必填
  //   size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
  //   corporateName: '调出公司', //公司label
  //   sectorName: '调出部门', //部门label
  //   cascaderShow: 'corporate', //配置部门不显示
  //   sectorNameLabelWidth: '78px',
  //   corporateNameLabelWidth: '78px',
  // })
  // const changeCascader4 = async (data: any) => {
  //   console.log(data)
  //   const { corporateId, corporateLabel, sectorLabel, sectorId } = data
  //   query.shiftCompanyName = corporateLabel
  //   query.shiftCompanyID = corporateId
  //   query.departmentName = sectorLabel
  //   query.departmentID = sectorId
  // }

  const acquisitionCompany = async () => {
    try {
      pageData.loadingUp = true
      let { code, message, data } = await post({
        url: 'admin/acl/user/findUserToken',
      })
      if (code == 200) {
        const { firmId, firmName, userName, department, departmentId, firmGroupId } = data.data
        query.shiftCompanyID = firmId
        query.shiftCompanyName = firmName
        query.shiftPerson = userName
        query.departmentID = departmentId
        query.departmentName = department
        query.companyID = firmGroupId
        pageData.showAdd = true
        pageData.loadingUp = false
        nextTick(() => {
          cascaderRef3.value?.parentComponent({
            sectorId: departmentId,
            corporateId: firmId,
            corporateLabel: firmName,
            sectorLabel: department,
          })
        })
        return
      }
      ElMessage.error(message)
    } finally {
      pageData.loadingUp = false
    }
  }
  const deleteData = () => {
    const selectedData = refgridOption.value.getSelectedRows()
    if (selectedData.length == 0) {
      ElMessage.warning('请勾选您要删除的单据')
      return
    }
    let condition = selectedData.every((item: any) => item.auditState == 1)
    if (condition) {
      ElMessage.warning('状态为审核通过不可删除!')
      return
    }
    ElMessageBox.confirm('确认删除选中单据?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          pageData.loadingUp = true
          let arr: any
          arr = []
          selectedData.map((item: any) => {
            arr.push(item.id)
          })
          let { code, message } = await post({
            url: 'purchase/FixedShift/delete',
            data: arr,
          })
          if (code == 200) {
            ElMessage.success('删除成功')
            pageData.loadingUp = false
            getList()
            return
          }
          ElMessage.error(message)
        } finally {
          pageData.loadingUp = false
        }
      })
      .catch(() => {})
  }
  const ruleFormRef = ref<any>()

  const save = async () => {
    const selectedData = refgridOption2.value.getListData()
    if (!query.inCompanyName) {
      ElMessage.warning('请选择转移公司')
      return
    }
    let stadey: boolean = true
    stadey = selectedData.every((item: any) => {
      return item.shiftDepartmentID
    })
    if (!stadey) {
      ElMessage.warning('请选择转移部门')
      return
    }

    if (selectedData.length == 0) {
      ElMessage.warning(`请勾选您的单据`)
      return
    }
    query.list = selectedData
    try {
      await ruleFormRef.value.validate()
      if (pageData.type == '新增') {
        try {
          pageData.loadingUp = true
          let { code, message } = await post({
            url: 'purchase/FixedShift/insert',
            data: query,
          })
          if (code == 200) {
            ElMessage.success('新增成功')
            pageData.loadingUp = false
            getList()
            pageData.showAdd = false
            return
          }
          ElMessage.error(message)
        } finally {
          pageData.loadingUp = false
        }
      }
      if (pageData.type == '修改') {
        let pam = query
        pam.id = pageData.id
        try {
          pageData.loadingUp = true
          let { code, message } = await post({
            url: 'purchase/FixedShift/update',
            data: pam,
          })
          if (code == 200) {
            ElMessage.success('修改成功')
            pageData.loadingUp = false
            getList()
            pageData.showAdd = false
            return
          }
          ElMessage.error(message)
        } finally {
          pageData.loadingUp = false
        }
      }
    } catch (error) {
      // 表单验证失败，可以执行相应的错误处理逻辑
    }
  }
  const TurnDown = () => {
    const selectedData = refgridOption.value.getSelectedRows()
    if (selectedData.length == 0) {
      ElMessage.warning('请勾选您要驳回的单据')
      return
    }
    if (selectedData.every((item: any) => item.auditState == 1)) {
      ElMessage.warning('状态为审核通过不可驳回!')
      return
    }
    ElMessageBox.confirm('确认驳回选中单据?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          pageData.loadingUp = true
          let arr: any
          arr = []
          selectedData.map((item: any) => {
            arr.push({
              id: item.id,
              auditState: '2',
            })
          })
          let { code, message } = await post({
            url: 'purchase/FixedShift/setAudit',
            data: arr,
          })
          if (code == 200) {
            ElMessage.success('驳回成功')
            pageData.loadingUp = false
            getList()
            return
          }
          ElMessage.error(message)
        } finally {
          pageData.loadingUp = false
        }
      })
      .catch(() => {})
  }
  const audit = () => {
    const selectedData = refgridOption.value.getSelectedRows()
    if (selectedData.length == 0) {
      ElMessage.warning('请勾选您要审核的单据')
      return
    }
    let condition = selectedData.every((item: any) => item.auditState == 1)
    if (condition) {
      ElMessage.warning('状态为审核通过不可审核!')
      return
    }
    ElMessageBox.confirm('确认审核选中单据?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          pageData.loadingUp = true
          let arr: any
          arr = []
          selectedData.map((item: any) => {
            arr.push({
              id: item.id,
              auditState: '1',
            })
          })
          let { code, message } = await post({
            url: 'purchase/FixedShift/setAudit',
            data: arr,
          })
          if (code == 200) {
            ElMessage.success('审核成功')
            pageData.loadingUp = false
            getList()
            // refgridOption.value.setQuery(query)
            return
          }
          ElMessage.error(message)
        } finally {
          pageData.loadingUp = false
        }
      })
      .catch(() => {})
  }
  onMounted(() => {
    getList()
    repairmanFocus()
    MaterialNameFocus()
    MaterialNameFocus1()
  })
  const getList = () => {
    if (pageData.active == 1) {
      form.auditState = 0
      nextTick(() => {
        refgridOption.value.setQuery(form)
      })
    }
    if (pageData.active == 2) {
      form.auditState = 1
      let pam = { ...form }
      pam.inCompanyName = pageData.companyName
      pam.inCompanyID = pageData.companyID
      pam.shiftDepartmentName = pageData.departmentName
      pam.shiftDepartmentID = pageData.departmentID
      pam.shiftPerson = pageData.needPerson
      pam.shiftCode = pageData.needCode
      pam.auditState = pageData.auditState == '' ? '12' : pageData.auditState
      nextTick(() => {
        refgridOption1.value.setQuery(pam)
      })
    }
  }

  const tabChange = (tab: any) => {
    emitter.emit('window-change')
    pageData.active = tab
    getList()
  }
  //机台
  let repairmanList = ref<any>([])
  //查询机台接口
  const repairmanFocus = async () => {
    try {
      pageData.loadingUp = true
      let res: any = await post({
        url: 'purchase/FixedInitialize/getFieldValue',
        data: {
          mechanicalCode: '',
        },
      })
      if (res.code == 200) {
        res.data.map((item: any) => {
          item.value = item.mechanicalCode
          item.label = item.mechanicalName + '-' + item.mechanicalCode
        })
        repairmanList.value = res.data
        pageData.loadingUp = false
        return
      }
      ElMessage.error(res.message)
    } finally {
      pageData.loadingUp = false
    }
  }
  const selectV2 = async (data: any) => {
    let pam = {
      mechanicalCode: '',
      mechanicalName: '',
    }
    repairmanList.value.map((item: any) => {
      if (item.mechanicalCode == data) {
        pam = {
          mechanicalCode: item.mechanicalCode,
          mechanicalName: item.mechanicalName,
        }
      }
    })
    query.mechanicalCode = pam.mechanicalCode
    try {
      pageData.loadingUp = true
      let { code, message, data } = await post({
        url: 'purchase/FixedInitialize/getList',
        data: pam,
      })
      if (code == 200) {
        const {
          district,
          mechanicalCode,
          deprecitionTime,
          upDeprecitionTime,
          joinFactoryTime,
          shiftShare,
          mechanicalName,
          difference,
        } = data
        query.shiftShare = shiftShare
        query.district = district
        query.scrapTime = deprecitionTime
        query.deprecitionTime = upDeprecitionTime
        query.joinFactoryTime = joinFactoryTime
        query.shiftShare = difference
        query.mechanicalCode = mechanicalCode
        query.mechanicalName = mechanicalName

        pageData.loadingUp = false
        return
      }
      ElMessage.error(message)
    } finally {
      pageData.loadingUp = false
    }
    console.log(pam)
  }

  // 获取部门列表
  const getBmGroup = (val: any) => {
    post({
      url: 'org/baCompany/getDepartmentTree?companyId=' + val,
    }).then((result) => {
      if (result.code === 200) {
        pageData.bmList = result.data
      }
    })
  }
</script>
<script lang="ts">
  export default defineComponent({
    name: 'BorrowingOfFixedAssets',
  })
</script>
<style scoped lang="less">
  .contioner {
    height: 100%;
    background-color: #fff;
  }

  .contentPrint {
    width: 100%;
    display: flex;
    justify-content: space-between;

    color: #000 !important;
  }

  .printLeft {
    width: 56%;
  }

  .printTitle {
    font-size: 22px;
    font-weight: 700;
    margin-top: 20px;
  }

  .printRight {
    width: 43%;
    display: flex;
    justify-content: space-between;
    flex-flow: row wrap;
  }

  .ermPrint {
    display: flex;
    justify-content: center;
    /* flex-flow: column wrap; */
    align-items: center;
  }

  .erm {
    width: 160px;
    height: 50px;
    background: #999;
  }

  .formPrint {
    display: flex;
    justify-content: space-between;
    flex-flow: row wrap;
  }

  .ban {
    width: 50%;
    margin-bottom: 5px;
  }

  .quan {
    width: 100%;
    margin-bottom: 5px;
  }

  table {
    text-align: center;
    color: #000;
  }

  td {
    color: #000;
  }

  th {
    color: #000;
  }

  .tablePrint {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    flex-flow: row wrap;
  }

  .footerPrint {
    display: flex;
    justify-content: space-around;
    margin-top: 8px;
    color: #000;
  }

  .createTime {
    width: 100px;
  }

  .printw {
    width: 30%;
    margin-bottom: 5px;
  }

  :deep(.el-dialog__body) {
    color: #000;
  }

  .my-tool-bar {
    background: #fff;
    padding: 18px;
  }

  .c-header {
    background: #fff;
    padding: 15px 0 10px 0;
  }

  :deep(.el-input__inner) {
    color: #3b3a3a;
  }

  :deep(.el-input__wrapper) {
    box-shadow: 0 0 0 1px #474849 inset;
  }

  :deep(.el-form-item__label) {
    color: #202021;
  }

  :deep(.arco-drawer-container) {
    z-index: 1000 !important;
  }

  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }

  :deep(.ag-header-group-text) {
    text-align: center;
  }

  :deep(.ag-header-group-cell-label, .ag-header-cell-label) {
    justify-content: center !important;
  }

  :deep(.ag-header-cell),
  :deep(.ag-header-group-cell) {
    border-right: 1px solid #dde2eb !important;
  }
</style>
